const log = require('../../utils/log');
const redisBase = require('../../common/RedisBase');
const gameCom = require("../gameCommon/gameCommon");
class ModeTz {
    constructor() {

    }

    static getInstance(){
        if(!ModeTz.instance){
            ModeTz.instance = new ModeTz();
            return ModeTz.instance;
        }else{
            return ModeTz.instance;
        }
    }

    //根据uid 取game_tz_info_list 列表里的数据
    async getUserInfoByUid(uid){
        let list = await redisBase.getGameTzInfoList();
        let res = null;
        for (let i = 0; i < list.length ; i++) {
            let cfg = JSON.parse(list[i]);
            if(cfg.uid === uid){
                res = cfg;
                break;
            }
        }
        return res;
    }

    //根据游戏类型 取game_tz_cfg_list 里的数据
    async getRewardList(gType){
        let list = await redisBase.getGameTzCfgList();
        let res = null;
        for (let i = 0; i < list.length; i++) {
            let cfg = JSON.parse(list[i]);
            if(cfg.gtype === gType){
                res = cfg;
            }
        }
        return res;
    }

    shuffleArray(arr) {
        if (!Array.isArray(arr)) {
            throw new Error('输入参数必须是一个数组');
        }

        const newArr = arr.slice(); // 创建一个新数组，避免修改原数组
        for (let i = newArr.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [newArr[i], newArr[j]] = [newArr[j], newArr[i]]; // 使用解构赋值交换元素
        }
        return newArr;
    }

    //取题目数据
    async getTopics(uid,count){
        //先判断redis 里面有没有
        //题目的数据
        let arr = [];
        let list=  await global.gameSerMgr.gameRedis.get_redis_topic_list_tz(uid);
        let topics = gameCom.getTidsByType();

        for (let i = 0; i < topics.length; i++) {
            let tid = topics[i];
            if(list.indexOf(tid.toString()) === -1){
                arr.push(tid)
            }
            if(arr.length >= count){
                break;
            }
        }

        //注意打乱顺序
        arr = this.shuffleArray(arr);

        return arr;
    }

    //添加已经答对的题目
    async addAsCurTid(uid,tid){
        await global.gameSerMgr.gameRedis.push_topic_to_list_tz(uid,tid);
    }

}
module.exports = ModeTz.getInstance();